<template>
  <div class="sth-fixed">
    <!-- 导航栏 -->
    <div class="tab-bar">
      <van-nav-bar left-arrow @click-left="$router.go(-1)" :border="false">
        <span class="headline" slot="title">代签文件.PDF</span>
      </van-nav-bar>
      <span class="company">{{ title }}</span>
    </div>
    <!-- 合同 -->
    <div class="contract-img">
      <div
        class="doc-page-content"
        :id="index + 1"
        v-for="(item, index) in contractImg"
        :key="index"
      >
        <img :src="'data:image/png;base64,' + item" alt="" />
      </div>
    </div>
    <!-- 底部按钮 -->
    <div class="sign-button">
      <span class="button-span" @click="signature">
        <van-icon
          class="icon-sketching"
          class-prefix="iconfont iconshouxieqianmingicon"
        />
        手写签名
      </span>
      <span class="button-span" @click="seal = true">
        <van-icon
          class="icon-sketching"
          class-prefix="iconfont iconweibiaoti--"
        />
        盖章
      </span>
      <van-button class="myButton" type="info" @click="immediately"
        >立即签署</van-button
      >
    </div>
    <!-- 手绘弹出层 -->
    <van-popup
      class="show-handwritten"
      v-model="ShowHandwritten"
      position="bottom"
      :style="{ height: '50%' }"
    >
      <div class="handwritten-head" @click="addHandwritten">
        <van-icon
          class="icon-handwritten"
          class-prefix="iconfont iconshouhuiqianmingicon"
        />
        直接手绘签名
      </div>
      <!-- 印章 -->
      <van-card
        centered
        class="handwritten-card"
        v-for="(item, index) in writeSignature.records"
        :key="index"
        @click="addDrag(item)"
      >
        <img slot="thumb" :src="item.sealImgData" alt="" />
        <span slot="desc">{{ item.sealName }}</span>
      </van-card>
    </van-popup>
    <!-- 盖章弹出窗 -->
    <van-popup class="seal" v-model="seal" position="bottom">
      <!-- 印章 -->
      <van-card
        centered
        title="合同专用章"
        desc="北京华信云盛科技有限公司"
        @click="addDrag"
      >
        <img slot="thumb" src="../../assets/公司印章.png" alt="" />
      </van-card>
      <van-card centered title="公章" desc="北京华信云盛科技有限公司">
        <img slot="thumb" src="../../assets/公司印章.png" alt="" />
      </van-card>
      <van-card centered title="公章" desc="北京华信云盛科技有限公司">
        <img slot="thumb" src="../../assets/公司印章.png" alt="" />
      </van-card>
    </van-popup>
    <!-- 签署校验 -->
    <van-popup
      round
      class="verify"
      v-model="verify"
      :close-on-click-overlay="false"
    >
      <div class="verify-box">
        <div class="verify-title">
          <span></span>
          签署校验
          <span></span>
        </div>
        <div class="verify-name">
          <span>请确认本人操作</span>
          <span>校验成功后即可完成文件签署</span>
        </div>
      </div>
      <van-form ref="sthForm">
        <van-field class="name-number" v-model="mobile" :readonly="true" />
        <van-field
          class="sms"
          center
          v-model="vcode"
          placeholder="请输入验证码"
        >
          <template #button>
            <van-button size="small" @click="getCode">获取验证码</van-button>
          </template>
        </van-field>
        <van-button class="btn-cancel" type="default" @click="verify = false"
          >取消</van-button
        >
        <van-button class="btn-confirm" type="default" @click="submitVerify"
          >确定</van-button
        >
      </van-form>
    </van-popup>
  </div>
</template>

<script>
import {
  addContractMessage,
  addContractPreview,
  addContractSignature,
  addContractFixed
} from '@/api/contract'
import { sendSms } from '@/api/user'
import { setItem, getItem } from '@/utils/storage'
export default {
  data() {
    return {
      // 待签名文件
      fileList: [],
      // 合同详情
      contractAllInfo: {},
      // 展示第一个文件
      curFile: {
        contractId: '',
        fileId: '',
        filePath: '',
        filePages: []
      },
      title: '',
      // 合同图片
      contractImg: [],
      curFileChangeFlag: false, // 监听当前文件改变状态
      // 合同页宽高
      width: 0,
      height: 0,
      // 手绘印章
      writeSignature: {},
      // 手绘弹出层显示隐藏
      ShowHandwritten: false,
      // 印章弹出窗
      seal: false,
      // 校验弹框显示
      verify: false,
      // 手机号码
      mobile: '',
      // 摘要
      contractId: '',
      bizNo: '',
      sealImg: '',
      authcWay: 2,
      // authcWay为1
      signsealPwd: '',
      // authcWay为2
      vcode: '',
      index: 0
    }
  },
  created() {
    if (this.$route.params.contractId) {
      setItem('contractId', this.$route.params.contractId)
    }
    this.contractId = this.$route.params.contractId || getItem('contractId')
    this.infoList()
    this.mobile = this.$store.state.userName.mobile
  },
  mounted() {
    this.contractId = this.$route.params.contractId
    this.bizNo = new Date().getTime()
  },
  updated() {
    if (this.curFileChangeFlag || this.index > 0) {
      this.initCompCoverControl()
      this.curFileChangeFlag = false
    }
  },
  methods: {
    async infoList() {
      await addContractMessage({ contractId: this.contractId }).then(res => {
        if (res.data.code !== '0') {
          return this.$toast.fail('数据获取失败')
        }
        this.contractAllInfo = res.data.data
        this.title = this.contractAllInfo.contractBaseInfo.title

        // 待签名文件列表
        const tempFileArr = []
        this.contractAllInfo.signingFileInfoList.forEach(item => {
          const file = {
            fileId: item.fileId,
            fileName: item.fileName,
            filePath: item.filePath,
            filePages: item.filePages
          }
          tempFileArr.push(file)
        })
        this.fileList = tempFileArr

        // 展示第一个文件
        this.curFile.contractId = this.contractAllInfo.contractBaseInfo.contractId
        this.curFile.fileId = this.fileList[0].fileId
        this.curFile.filePath = this.fileList[0].filePath
        const pages = []
        for (var i = 0; i <= this.fileList[0].filePages; i++) {
          pages.push(i + 1)
        }
        this.curFile.filePages = pages
      })
      for (let i = 1; i < this.curFile.filePages.length; i++) {
        await addContractPreview({
          // contractId: this.curFile.contractId,
          filePath: this.curFile.filePath,
          pageNum: i
        }).then(res => {
          if (res.data.code !== '0') {
            return this.$toast.fail('图片获取失败!')
          }
          this.contractImg.push(res.data.data)
        })
      }
    },
    // 电子签名请求
    async signature() {
      this.ShowHandwritten = true
      try {
        await addContractSignature({
          idNumber: this.$store.state.userName.idNumber
        }).then(res => {
          if (res.data.code !== '0') {
            return this.$toast.fail('手写获取失败')
          }
          this.writeSignature = res.data.data
          if (this.writeSignature.records.length === 0) {
            this.$toast('没有手绘签名')
          }
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 手写签名点击事件
    addHandwritten() {
      this.$router.push('/canvas')
    },
    // 选择印章
    addDrag(item) {
      this.seal = false
      this.ShowHandwritten = false
      this.sealImg = item.sealImgData
      const box = document.querySelector('.control-signseal')
      const sealImgEle = `<img src="${this.sealImg}" style="width:${box.clientWidth}px;height:${box.clientHeight}px" />`
      box.innerHTML = sealImgEle
    },
    // 点击立即签署
    immediately() {
      if (this.sealImg === '') {
        return this.$toast('请先放置印章')
      }
      this.verify = true
    },
    // 需要加盖的印章位置
    initCompCoverControl() {
      const div = document.getElementById('1')
      this.width = div.offsetWidth
      this.height = div.offsetHeight
      const signingCoordArr = []
      const contractBaseInfo = this.contractAllInfo.contractBaseInfo
      // 当前签署人需要加盖的印章位置
      this.contractAllInfo.signingFileCoordInfoList.forEach(item => {
        // 企业签署
        if (contractBaseInfo.curSignerType === 1) {
          if (
            item.signerType === 1 &&
            contractBaseInfo.curOrgIdnumber === item.orgIdnumber
          ) {
            if (contractBaseInfo.curUserIdnumber === item.userIdnumber) {
              signingCoordArr.push(item)
            }
          }
        } else if (contractBaseInfo.curSignerType === 2) {
          // 个人签署
          if (
            item.signerType === 2 &&
            contractBaseInfo.curUserIdnumber === item.userIdnumber
          ) {
            signingCoordArr.push(item)
          }
        }
      })
      // 合同印章位置

      for (var key in signingCoordArr) {
        const item = signingCoordArr[key]
        const id = item.id
        const xpercent = item.xpercent
        const ypercent = item.ypercent
        const pageNum = item.filePageNumber
        const signerType = item.signerType

        const posLeft = ((xpercent * this.width) / 100).toFixed(2)
        const posTop = (this.height - (ypercent * this.height) / 100).toFixed(2)

        let width = 0
        let height = 0
        // 企业盖公章
        if (signerType === 1) {
          width = this.width * 0.190476 + 'px'
          height = width
        } else if (signerType === 2) {
          // 个人名章
          width = this.width * 0.095 + 'px'
          height = this.height * 0.048 + 'px'
        }

        const div = document.createElement('div')
        div.id = id
        div.innerHTML = ''
        div.style.width = width
        div.style.height = height
        div.style.zIndex = '4'
        div.style.left = posLeft + 'px'
        div.style.top = posTop + 'px'
        div.className = 'control-signseal'

        const addSeal = document.getElementById(pageNum)
        addSeal.appendChild(div)
      }
    },
    // 表单提交事件
    async submitVerify() {
      this.verify = false
      this.$toast.loading({
        message: '正在签署...',
        forbidClick: true
      })
      const param = {
        contractId: this.contractId,
        bizNo: this.bizNo,
        sealImg: this.sealImg.replace(/^data:image\/\w+;base64,/, ''),
        authcWay: this.authcWay,
        vcode: this.vcode
      }
      await addContractFixed(param).then(res => {
        console.log(res)
        if (res.data.code !== '0') {
          this.verify = false
          return this.$toast.fail(res.data.msg)
        }
        this.$toast.success('签署成功')
        this.$router.push({
          name: 'authentication',
          params: { contractId: this.contractId }
        })
      })
    },
    // 获取验证码
    async getCode() {
      try {
        const { data: res } = await sendSms(this.mobile)
        if (res.code !== '0') {
          return this.$toast.fail('发送短信失败')
        }
      } catch (error) {
        console.log(error)
      }
    }
  },
  watch: {
    curFile: {
      handler: function(val, oldval) {
        this.index++
        this.curFileChangeFlag = true
      },
      deep: true // 对象内部的属性监听，也叫深度监听
    }
  }
}
</script>

<style scoped lang="less">
.sth-fixed {
  padding: 168px 0 120px;
  .tab-bar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 88px;
    background-color: #fff;
    z-index: 33;
    .van-nav-bar {
      .headline {
        font-size: 34px;
        font-weight: bold;
      }
      /deep/.van-icon {
        font-size: 40px;
        color: #101010;
      }
    }
    /deep/.van-nav-bar__left {
      padding-left: 23px;
    }
    .company {
      font-size: 26px;
      display: block;
      box-sizing: border-box;
      height: 80px;
      line-height: 80px;
      padding-left: 41px;
      border-bottom: 1px solid #e0e0e0;
      color: #2c2c2c;
      background-color: #fff;
    }
  }
  // 合同
  .contract-img {
    height: 78.4vh;
    .doc-page-content {
      position: relative;
      img {
        display: block;
        width: 100%;
      }
      /deep/.control-signseal {
        text-align: center;
        position: absolute;
        border: 1px dashed rgb(0, 175, 161);
      }
    }
  }
  // 按钮
  .sign-button {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 120px;
    line-height: 120px;
    border-top: 1px solid #e0e0e0;
    background-color: #fff;
    .button-span {
      font-size: 24px;
      margin-left: 40px;
      .icon-sketching {
        font-size: 35px;
      }
      .iconfont {
        margin-right: 13px;
        vertical-align: middle;
      }
    }
    .myButton {
      position: absolute;
      width: 280px;
      height: 80px;
      right: 40px;
      top: 20px;
    }
  }
  // 手绘
  .show-handwritten {
    .handwritten-head {
      height: 100px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 28px;
      color: #2489f2;
      border-bottom: 1px solid #e4e4e4;
      .icon-handwritten {
        font-size: 30px;
        margin-right: 11px;
      }
    }
    .van-card:not(:first-child) {
      margin-top: 0;
    }
    .handwritten-card {
      .van-card__thumb {
        width: 200px;
        height: 168px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        border: 1px solid red;
        border-radius: 6px;
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .seal {
    height: 561px;
    .van-card__thumb {
      margin: 52px 52px 52px 100px !important;
    }
    .van-card__title {
      font-weight: bold;
      font-size: 30px;
      margin-bottom: 22px;
    }
    .van-card:not(:first-child) {
      margin-top: 0;
    }
  }
  // 底部按钮
  .van-card {
    padding: 0;
    background-color: #fff;
    border-bottom: 1px solid #e4e4e4;
    .van-card__thumb {
      margin: 61px 86px 61px 85px;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
  // 校验
  .verify {
    width: 560px;
    height: 561px;
    background-color: #fff;
    text-align: center;
    .verify-box {
      box-sizing: border-box;
      height: 234px;
      padding-top: 49px;
      .verify-title {
        font-size: 34px;
        margin-bottom: 23px;
        span {
          display: inline-block;
          height: 1px;
          width: 30px;
          background-color: #000;
          margin: 0 18px;
          vertical-align: middle;
        }
      }
      .verify-name {
        display: flex;
        flex-direction: column;
        span:nth-child(1) {
          font-size: 30px;
          margin-bottom: 15px;
        }
        span:nth-child(2) {
          font-size: 26px;
          color: #999999;
        }
      }
    }
    .van-form {
      padding: 0 32px;
      .name-number {
        height: 84px;
        background-color: #f2f2f2;
        margin-bottom: 24px;
        border: 1px solid #dadada;
      }
      .sms {
        height: 84px;
        border: 1px solid #dadada;
        padding-right: 0;
        .van-button--small {
          width: 189px;
          height: 40px;
          font-size: 30px;
          vertical-align: middle;
          border-width: 0;
          border-left: 1px solid #dadada;
          color: #666666;
        }
      }
      .btn-cancel {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 50%;
        border-right: 0;
      }
      .btn-confirm {
        width: 50%;
        position: absolute;
        right: 0;
        bottom: 0;
      }
    }
  }
}
</style>
